package com.etc.security.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.etc.common.Code;
import com.etc.common.CodeMessage;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * Filename:    JWTAccessDeniedHandler.java  
 * Description:  统一exceptionhandl 没有访问权限
 * Copyright:   Copyright (c) 2018-2019 All Rights Reserved.
 * Company:     chinasofti.com Inc.
 * @author:     mazheng 
 * @version:    1.0  
 * Create at:   2020年3月4日 下午3:40:42  
 *  
 * Modification History:  
 * Date         Author      Version     Description  
 * ------------------------------------------------------------------  
 * 2020年3月4日      mazheng      1.0         1.0 Version  
 *
 */
public class JWTAccessDeniedHandler implements AccessDeniedHandler {
    
    
    private static final Logger logger = LoggerFactory.getLogger(JWTAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        logger.warn(e.getMessage());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
//        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString( CodeMessage.faild(Code.FAIL_AUTHORIZATION, "権限がありません")));
    }
}
